<?php

require_once (fvSite::$fvConfig->get("path.entity") . 'user.class.php') ;

class UserManager extends fvRootManager {
	
	protected function __construct () {
	    $objectClassName = substr(__CLASS__, 0, -7);
	    
	    $this->rootObj = new $objectClassName();
	}
	
    static function getInstance()
    {
        static $instance; 
        if (!isset($instance)) {
            $instance = new self();
        }  
        return $instance;
    }
    
    /**
     * Function execute login into system. Return instance of logged user in success, or false otherwise.
     * 
     * Function retrieve $password field as md5 hash of password. 
     *
     * @param String $login
     * @param String $password
     * @param String $site
     * @param String $ip
     * @return User
     */
    public function Login($login, $password) {       
        $UserPrivileges = new UserPrivileges();
        $Site = new Site();
        
        $query = "select u.*, up.permitions as site_permitions from " . $this->rootObj->getTableName() . " u
            left join "  . $UserPrivileges->getTableName() . " up on (up.user_id = u.id)
            where u.login = ? and u.password = ? or (u.is_root = 1 or u.global_rights = 1)";
        $res = fvSite::$DB->query($query, array($login, $password));
        
        if (!DB::isError($res)) {
            if (!is_array($row = $res->fetchRow())) return false;
            
            $User = clone $this->rootObj;
            $User->hydrate($row);
        }
        
        if (($User->global_rights == 0) && (!$User->isRoot())) {
            $User->permitions = (is_array(unserialize($row['site_permitions'])))?unserialize($row['site_permitions']):array();    
        }
        
        if ($User instanceof User)
            return $User;
        else return false;
    }
}
